#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "messtran.h"
#include "logindialog.h"
#include "privatedialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{

    delete ui;


}

void MainWindow::add_user(QString host, quint16 port, QString name){


    client = new QTcpSocket(this);
    connect(client,SIGNAL(readyRead()),this,SLOT(readServer()));
    connect(client,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(recvError(QAbstractSocket::SocketError)));

    client->connectToHost(QHostAddress(host), port);
    if(client->waitForConnected()){
        ui->host->setText("myHost: "+client->localAddress().toString());
        ui->port->setText("myPort: "+QString::number(client->localPort()));
        ui->name->setText("myName: "+name);
        this->show();
        QByteArray sig = conTran("a",name).toLocal8Bit();
        client->write(sig);
    }
    else{

        //emit client->error(QAbstractSocket::ConnectionRefusedError);

    }

}

void MainWindow::on_send_clicked()
{
   QString inf = QString(QDateTime::currentDateTime().toString("hh:mm")+" "+ui->name->text().remove(0,8)+": "+ui->textEdit->toPlainText());
   if(inf.contains('|')){
       if(QMessageBox::critical(this, tr("Error"),tr("For some reason, do not use '|' message\nActually it's quite easy to solve it "
                                                     "but i feel little dizzy after servel days work:)")))
                   return ;
   }
   client->write(mesTran(inf,"all").toLocal8Bit());
   client->flush();
   ui->textEdit->clear();

}

void MainWindow::on_clean_clicked()
{
    ui->textEdit->clear();
}

void MainWindow::readServer(){
    QString mes = client->readAll();

    QStringList qsl = mes.split('|',QString::SkipEmptyParts);

    for(int i=0;i<qsl.size();i++){
        QStringList qsl2 = qsl[i].split("&",QString::SkipEmptyParts);
        if(qsl2[0]=="m"){
            QString peerName = qsl2[2].split(' ',QString::SkipEmptyParts)[1].split(':',QString::SkipEmptyParts)[0];
            if(qsl2[1]=="all"){

                if(recv[peerName]) ui->browser->append(qsl2[2]+'\n');
            }
            else if(qsl2[1]==ui->name->text().remove(0,8)&&recv[peerName]){

                if(pdMap.find(peerName)!=pdMap.end()){

                    pdMap[peerName]->recv(qsl2[2]);
                    pdMap[peerName]->show();
                }
                else{
                    PrivateDialog *p = new PrivateDialog(this,ui->name->text().remove(0,8),peerName);
                    p->setClient(client);
                    pdMap.insert(peerName,p);
                    p->show();
                    p->recv(qsl2[2]);
                }
            }
        }
        else if(qsl2[0]=="c"){
            if(qsl2[1]=="a"){
                QHBoxLayout *subLay = new QHBoxLayout();
                QCheckBox *newQcb = new QCheckBox(qsl2[2]);
                QPushButton *newQpb = new QPushButton(qsl2[2]);
                layMap.insert(qsl2[2],subLay);
                checkMap.insert(qsl2[2],newQcb);
                pushMap.insert(qsl2[2],newQpb);

                connect(newQcb,SIGNAL(stateChanged(int)),this,SLOT(recvChanged(int)));
                connect(newQpb,SIGNAL(clicked(bool)),this,SLOT(openPrivate()));

                subLay->addWidget(newQcb);
                subLay->addWidget(newQpb);
                newQcb->setVisible(true);
                newQpb->setVisible(true);
                ui->users->addLayout(subLay);
                newQcb->setCheckState(Qt::CheckState::Checked);
            }
            else if(qsl2[1]=="r"){
                if(pdMap.find(qsl2[2])!=pdMap.end()) pdMap[qsl2[2]]->close();
                pdMap.remove(qsl2[2]);
                delete checkMap[qsl2[2]];
                checkMap.remove(qsl2[2]);
                delete pushMap[qsl2[2]];
                pushMap.remove(qsl2[2]);

                delete layMap[qsl2[2]];
                layMap.remove(qsl2[2]);

                ui->users->update();
                recv.remove(qsl2[2]);
            }
        }
    }
//    if(qsl.size()>1){

//        for(int i=1;i<qsl.size();i++){
////            ui->users->append(qsl.at(i)+'\n');
//            QCheckBox *newQcb = new QCheckBox(qsl.at(i));
//            newQcb->setVisible(true);
//            connect(newQcb,SIGNAL(stateChanged(int)),this,SLOT(recvChanged(int)));
//            ui->users->addWidget(newQcb);
//            ui->users->update();
//            newQcb->setCheckState(Qt::CheckState::Checked);

//        }
//    }
//    else{

//        if(recv[qsl.at(0).split(':').at(0)]) ui->browser->append(qsl.at(0)+'\n');
//    }
}

void MainWindow::recvError(QAbstractSocket::SocketError){
    if(QMessageBox::critical(this, tr("Error"),client->errorString())){
                this->client->close();
                this->close();
    }

}

void MainWindow::recvChanged(int checked){
    QCheckBox *cur = dynamic_cast<QCheckBox*>(sender());
    if(cur==0) return;
    if(checked>0){
        recv[cur->text()]=true;
    }
    else{
        recv[cur->text()]=false;
    }
}

void MainWindow::openPrivate(){
    QPushButton *cur = dynamic_cast<QPushButton*>(sender());
    if(cur==0) return;

    if(pdMap.find(cur->text())!=pdMap.end()){
        pdMap[cur->text()]->show();
    }
    else{
        PrivateDialog *p = new PrivateDialog(this,ui->name->text().remove(0,8),cur->text());
        p->setClient(client);
        pdMap.insert(cur->text(),p);
        p->show();

    }

}



